/**
 * Multi-language related operations
 */
import i18n from "./setupI18n";
import { loadLocalePool, setHtmlPageLang } from "./helper";
import type { LocaleType } from "@/types/config";
// import { useLocaleStoreWithOut } from "@/store/modules/locale";
import { useMemo } from "react";
import { store } from "@/redux";
// import { setLanguage } from "@/redux/modules/global/action";

interface LangModule {
	message: Recordable;
	dateLocale: Recordable;
	dateLocaleName: string;
}

function setI18nLanguage(locale: LocaleType) {
	// const localeStore = useLocaleStoreWithOut();

	// if (i18n.mode === "legacy") {
	// 	i18n.global.locale = locale;
	// } else {
	// 	(i18n.global.locale as any).value = locale;
	// }
	// setLanguage(locale);
	setHtmlPageLang(locale);
}

export function useLocale() {
	const { language } = store.getState().global;
	// const localeStore = useLocaleStoreWithOut();
	const getLocale = useMemo(() => language, [language]);
	// const getShowLocalePicker = computed(() => localeStore.getShowPicker);

	const getAntdLocale = useMemo((): any => {
		const localeMessage = i18n.getDataByLanguage(getLocale);
		return localeMessage?.translation?.antdLocale ?? {};
	}, [getLocale]);

	// Switching the language will change the locale of useI18n
	// And submit to configuration modification
	async function changeLocale(locale: LocaleType) {
		const currentLocale = i18n.language;
		console.log("currentLocale-1", locale, currentLocale);
		if (currentLocale === locale) return locale;

		console.log("loadLocalePool-2", loadLocalePool);
		if (loadLocalePool.includes(locale)) {
			// setI18nLanguage(locale);
			i18n.changeLanguage(locale);
			return locale;
		}
		const langModule = (await import(`./lang/${locale}.ts`)).default as LangModule;
		if (!langModule) return;

		// const { message } = langModule;
		// globalI18n.setLocaleMessage(locale, message);
		console.log("langModule-3", langModule);
		i18n.addResourceBundle(locale, "translation", langModule);
		i18n.changeLanguage(locale);
		loadLocalePool.push(locale);

		setI18nLanguage(locale);
		return locale;
	}

	return {
		getLocale,
		// getShowLocalePicker,
		changeLocale,
		getAntdLocale
	};
}
